package com.hulu.yec.common.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hulu.yec.common.Constant;
import com.hulu.yec.sys.service.SysDao;
import com.hulu.yec.sys.user.entity.SysUserEntity;

@WebServlet("/CommonServlet")
public class CommonServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static SysDao sysDao = new SysDao();

	public CommonServlet() {
		super();
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding(Constant.ENCODING_UTF8);
		String command = request.getParameter("command");
		if ("login".equals(command)) {
			login(request, response);
		} else if ("logOut".equals(command)) {
			logOut(request, response);
		} else if ("goLogin".equals(command)) {
			goLogin(request, response);
		} else if ("myinformation".equals(command)) {
			myinformation(request, response);
		} else if ("listById".equals(command)) {
			listById(request, response);
		} else if ("update".equals(command)) {
			update(request, response);
		}else if("updatePassword".equals(command)){
			updatePassword(request,response);
		} else if ("lookupPassword".equals(command)) {
			lookupPassword(request, response);
		} else if ("modifyPassword".equals(command)) {
			modifyPassword(request, response);
		}else if("verificationEmail".equals(command)){
			verificationEmail(request,response);
		}else if("verificationPhone".equals(command)){
			verificationPhone(request,response);
		}
	}

	/**
	 * 
	 * 系统管理员登录
	 * 
	 * @param request
	 * 
	 * @param response
	 * 
	 * @throws ServletException
	 * 
	 * @throws IOException
	 * 
	 */
	private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String code = request.getParameter("code");
		String password = request.getParameter("password");

		String rememberLogin = request.getParameter("rememberLogin");

		String checkCode = request.getParameter("j_captcha");
		String checkPwd = (String) request.getSession()
				.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);

		if (checkPwd != null && !checkPwd.equals(checkCode)) {
			request.setAttribute("code", code);
			request.setAttribute("errorInfo", "验证码错误！");
			request.getRequestDispatcher("/WEB-INF/view/common/login.jsp").forward(request, response);
		}
		SysUserEntity user = sysDao.login(code, password);
		if (user == null) {
			request.setAttribute("code", code);
			request.setAttribute("errorInfo", "用户名或密码错误！");
			request.getRequestDispatcher("/WEB-INF/view/common/login.jsp").forward(request, response);
		} else if (user.getState() != 1) {
			request.setAttribute("errorInfo", "用户无效");
			request.getRequestDispatcher("/WEB-INF/view/common/login.jsp").forward(request, response);
		} else {
			useCookie(request, response, code, password, rememberLogin);
			request.getSession().setAttribute("user", user);
			request.getRequestDispatcher("/WEB-INF/view/sys/main.jsp").forward(request, response);
		}
	}

	/**
	 * 
	 * 系统注销
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void logOut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Cookie[] cook = request.getCookies();
		for (int i = 0; i < cook.length; i++) {

			if ("code".equals(cook[i].getName())) {
				Cookie cooks = new Cookie("code", null);
				response.addCookie(cooks);
			}
			if ("password".equals(cook[i].getName())) {
				Cookie cooks = new Cookie("password", null);
				response.addCookie(cooks);
			}
			if ("rememberLogin".equals(cook[i].getName())) {
				Cookie cooks = new Cookie("rememberLogin", null);
				response.addCookie(cooks);
			}
		}
		request.getSession().invalidate();

		request.getRequestDispatcher("/WEB-INF/view/sys/main.jsp").forward(request, response);
	}

	/**
	 * 使用Cookie
	 * 
	 * @param request
	 * @param response
	 * @param code
	 * @param password
	 * @param rememberLogin
	 * @throws UnsupportedEncodingException
	 */
	private void useCookie(HttpServletRequest request, HttpServletResponse response, String code, String password,
			String rememberLogin) throws UnsupportedEncodingException {

		if ("true".equals(rememberLogin)) {
			// 设置Cookie
			Cookie usernameCookie = new Cookie("code", URLEncoder.encode(code, Constant.ENCODING_UTF8));
			// 如果没有设置存活时间（单位为：秒），Cookie在浏览器关闭就会失效，也并不会存入硬盘
			usernameCookie.setMaxAge(60 * 30);
			response.addCookie(usernameCookie);
			Cookie passwordCookie = new Cookie("password", password);
			// 如果没有设置存活时间，Cookie在浏览器关闭就会失效，也并不会存入硬盘
			passwordCookie.setMaxAge(60 * 30);
			response.addCookie(passwordCookie);
			Cookie rememberLoginCookie = new Cookie("rememberLogin", rememberLogin);
			// 如果没有设置存活时间，Cookie在浏览器关闭就会失效，也并不会存入硬盘
			rememberLoginCookie.setMaxAge(60 * 30);
			response.addCookie(rememberLoginCookie);
		}
	}

	/**
	 * 跳转到系统管理员登录界面
	 *
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void goLogin(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/view/common/login.jsp").forward(request, response);
	}

	/**
	 * 个人信息查看
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void myinformation(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获取前台参数
		SysUserEntity user = (SysUserEntity) request.getSession().getAttribute("user");
		int id = user.getId();

		// 调用业务逻辑
		// 获取用户表中的roleId
		List<SysUserEntity> roleId = sysDao.roleIdlist(id);
		int row = roleId.get(0).getRoleId();

		List<SysUserEntity> myinformationList = sysDao.list(id);
		List<SysUserEntity> studentinformationList = sysDao.list1(id);

		// 转向
		if (row != 1 && row != 2) {
			request.setAttribute("studentinformationList", studentinformationList);
			request.getRequestDispatcher("/WEB-INF/view/common/studentinformation.jsp").forward(request, response);

		} else {
			request.setAttribute("myinformationList", myinformationList);
			request.getRequestDispatcher("/WEB-INF/view/common/myinformation.jsp").forward(request, response);
		}
	}

	/**
	 * 修改之前用户信息查询
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void listById(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// 获取前台存到session中的id
		SysUserEntity user = (SysUserEntity) request.getSession().getAttribute("user");
		int id = user.getId();
		// 调用UserDao中用户编号获取用户信息 逻辑业务
		List<SysUserEntity> roleId = sysDao.roleIdlist(id);
		int row = roleId.get(0).getRoleId();
		SysUserEntity sysUser = sysDao.listById(id);
		SysUserEntity studentUser = sysDao.studentListById(id);
		// 转向
		if (row != 3) {
			request.setAttribute("sysUser", sysUser);
			request.getRequestDispatcher("/WEB-INF/view/common/update.jsp").forward(request, response);

		} else {
			request.setAttribute("studentUser", studentUser);
			request.getRequestDispatcher("/WEB-INF/view/common/studentupdate.jsp").forward(request, response);
		}
	}

	/**
	 * 用户信息的修改
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 获取前台传来的参数
		SysUserEntity user = (SysUserEntity) request.getSession().getAttribute("user");
		int id = user.getId();
		String phone = request.getParameter("phone");
		String email = request.getParameter("email");
		// 把获取的信息封装到SysUserEntity对象中
		SysUserEntity sysUserEntity = new SysUserEntity();
		sysUserEntity.setId(id);
		sysUserEntity.setPhone(phone);
		sysUserEntity.setEmail(email);
		// 调用userDao中添加用户信息的方法
		int row = sysDao.update(sysUserEntity);
		if (row >= 1) {
			request.getRequestDispatcher("CommonServlet?command=myinformation").forward(request, response);
			;
		} else {
			request.getRequestDispatcher("CommonServlet?command=listById").forward(request, response);
		}
	}
	
	/**
	 * top的jsp跳转到修改密码页面
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void updatePassword(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/view/common/password.jsp").forward(request, response);			
		
	}
	
	/**
	 * 邮箱验证
	 * @param request
	 * @param response
	 * @throws IOException 
	 */

	private void verificationEmail(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String email = request.getParameter("email");
	    List<SysUserEntity> UserEmail = sysDao.verification(email);
	    SysUserEntity sysUserEntity = new SysUserEntity();
	    sysUserEntity.setEmail(email);
		response.setCharacterEncoding(Constant.ENCODING_UTF8);
		PrintWriter printWriter = response.getWriter();
		try{
			if(UserEmail.size() > 0){
				printWriter.print(1);
			}else{
				printWriter.print(0);
			}
			
		}finally {
			printWriter.close();
		  }
	    }
	/**
	 * 电话验证
	 * 
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	private void verificationPhone(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String phone = request.getParameter("phone");
	    List<SysUserEntity> UserPhone = sysDao.verificationPhoen(phone);
	    SysUserEntity sysUserEntity = new SysUserEntity();
	    sysUserEntity.setEmail(phone);
		response.setCharacterEncoding(Constant.ENCODING_UTF8);
		PrintWriter printWriter = response.getWriter();
		try{
			if(UserPhone.size() > 0){
				printWriter.print(1);
			}else{
				printWriter.print(0);
			}
			
		}finally {
			printWriter.close();
		  }
	    }
		
	
	/**
	 * 修改前的密码查询
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void lookupPassword(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取存在session中的id
	
		SysUserEntity user = (SysUserEntity) request.getSession().getAttribute("user"); 
		String oldpassword = request.getParameter("oldpassword");
		
		int id = user.getId();
		 
		 
		List<SysUserEntity> look = sysDao.lookupPassword(id,oldpassword);
		//转向
		response.setCharacterEncoding(Constant.ENCODING_UTF8);
		 if(look.size() != 0){
			 String info = "　　通过!";
				response.getWriter().print(info);
		 }else{
			 String info = "　　错误!";
			 response.getWriter().print(info);
		 }
    }
			
		
	/**
	 * 修改密码
	 * 
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void modifyPassword(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取前台传来的参数
		SysUserEntity user = (SysUserEntity) request.getSession().getAttribute("user");
		int id = user.getId();
		String  newPassword = request.getParameter("user[pwd]");
		// 把获取的信息封装到SysUserEntity对象中
		SysUserEntity sysUser = new SysUserEntity();
		sysUser.setId(id);
		sysUser.setPassword(newPassword);
		int row = new SysDao().modifyPassword(id,newPassword);
	
		//转向
		if(row >= 1){
			request.getRequestDispatcher("CommonServlet?command=goLogin").forward(request, response);
		}else{
			request.getRequestDispatcher("/WEB-INF/view/common/password.jsp").forward(request, response);
		}
	}
}
